package cn.lx.auth.secutity.handler;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName RedirectAuthenticationSuccessHandler
 * @Description: //todo
 * @Author: 落雪
 * @CreateDate: 2025/7/14 23:23
 * @UpdateUser: 落雪
 * @UpdateDate: 2025/7/14 23:23
 * @UpdateRemark:
 * @Version: 1.0
 */
public class RedirectAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    private RequestCache requestCache = new HttpSessionRequestCache();

    public RedirectAuthenticationSuccessHandler() {
    }
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        String hasfRedirect = request.getParameter("hasf_redirect_uri");
        if (null != hasfRedirect) {
            this.getRedirectStrategy().sendRedirect(request, response, hasfRedirect);
        } else {
            SavedRequest savedRequest = this.requestCache.getRequest(request, response);
            if (savedRequest == null) {
                super.onAuthenticationSuccess(request, response, authentication);
            } else {
                String targetUrlParameter = this.getTargetUrlParameter();
                if (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter))) {
                    this.requestCache.removeRequest(request, response);
                    super.onAuthenticationSuccess(request, response, authentication);
                } else {
                    this.clearAuthenticationAttributes(request);
                    String targetUrl = savedRequest.getRedirectUrl();
                    this.getRedirectStrategy().sendRedirect(request, response, targetUrl);
                }
            }
        }
    }
}

